package com.kasax.imgloader.demo.utils;

import com.kasax.imgloader.demo.api.ApiService;
import com.kasax.imgloader.demo.Constants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetofitHelper {
    private static final int TIME_OUT = 180;

    private static Retrofit retrofit;

    private static String defaultHost = Constants.BASE_URL;

    private static OkHttpClient okHttpClient;

    static {
        okHttpClient = new OkHttpClient
                .Builder()
                .callTimeout(TIME_OUT, TimeUnit.SECONDS)
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
//                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
    }

    public static <T> T createService(Class<T> serviceApi) {
        if (serviceApi == null) {
            return null;
        }

        retrofit = new Retrofit
                .Builder()
                .baseUrl(defaultHost)
                .client(okHttpClient)
//                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(serviceApi);
    }

    public static ApiService createApiService() {
        return createService(ApiService.class);
    }
}
